package com.tianji.chat.storage.impl;

import com.tianji.chat.storage.IFileStorage;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileStorageImpl implements IFileStorage {


    @Override
    public String uploadFile(MultipartFile file){
        try {
            if (file.isEmpty()){
                return "文件为空";
            }
            //获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名："+fileName);
            //获取文件后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("文件后缀名："+suffixName);
            //设置文件存储路径
//            String filePath = "f:/upload/";
            String filePath = ResourceUtils.getURL("classpath:").getPath() + "static/files/";
            String path = filePath+fileName;
            File dest = new File(path);
            //检测是否存在该目录
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            //写入文件并返回路径
            file.transferTo(dest);
            return dest.toString();
        } catch (IOException e) {
            log.error("文件写入异常", e);
        }
        return "-1";
    }



    @Override
    public InputStream downloadFile(String key) {
        return null;
    }

    @Override
    public void deleteFile(String key) {

    }

    @Override
    public void deleteFiles(List<String> keys) {

    }
}
